<!DOCTYPE html>
<html lang="zh-CN">

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!-- 引入 Bootstrap v3 的 CSS 文件 -->
	<link rel="stylesheet" href="bootstrap-3.4.1/css/bootstrap.css">
	<!-- 引入 jQuery（Bootstrap v3 依赖） -->
	<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
	<!-- 引入 Bootstrap v3 的 JS 文件 -->
	<script src="bootstrap-3.4.1/js/bootstrap.js"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.9.0/axios.js"></script>
	<title>权限管理</title>
	<style>
		#cancel {
			font-size: 20px;
			padding: 5px 10px;
			color: blueviolet;
			cursor: pointer;
		}

		.form-control {
			border-radius: 8px;
			padding: 12px 15px;
			height: auto;
			border: 1px solid #dce4ec;
			transition: all 0.3s ease;
		}

		.form-control:focus {
			border-color: #3498db;
			box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.15);
		}

		#note {
			resize: none;
		}
	</style>

</head>

<body>

	<nav class="navbar navbar-default">
		<div class="container-fluid">
			<!-- Brand and toggle get grouped for better mobile display -->
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
					data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
					<span class="sr-only">Toggle navigation</span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">权限管理</a>
			</div>

			<!-- Collect the nav links, forms, and other content for toggling -->
			<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
				<form class="navbar-form navbar-left">
					<div class="form-group">
						<input type="text" class="form-control" placeholder="权限类型">
					</div>
					<div class="form-group">
						<input type="text" class="form-control" placeholder="权限名称">
					</div>
					<div class="form-group">
						<select class="form-control">
							<option value="-1">所有</option>
							<option value="0">启用</option>
							<option value="1">禁用</option>
						</select>
					</div>
					<button class="btn btn-default">查询</button>
				</form>
				<ul class="nav navbar-nav navbar-right">
					<li><a href="#" data-toggle="modal" data-target="#addDictModal">添加权限</a></li>
					<li class="dropdown">
						<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
							aria-expanded="false">Dropdown <span class="caret"></span></a>
						<ul class="dropdown-menu">
							<li><a href="#">Action</a></li>
							<li><a href="#">Another action</a></li>
							<li><a href="#">Something else here</a></li>
							<li role="separator" class="divider"></li>
							<li><a href="#">Separated link</a></li>
						</ul>
					</li>
				</ul>
			</div><!-- /.navbar-collapse -->
		</div><!-- /.container-fluid -->
	</nav>
	<!-- 角色管理的表格 -->
	<table class="table table-bordered table-striped table-condensed">
		<thead>
			<th>#</th>
			<th>角色名称</th>
			<th>角色描述</th>
			<th>角色状态</th>
			<th>创建时间</th>
			<th>更新时间</th>
			<th>创建人</th>
			<th>更新人</th>
			<th>操作</th>
		</thead>
		<tbody id="dict-tbody">
			<!-- 动态插入数据 -->
		</tbody>

		<tfoot>
			<tr>
				<td colspan="7" style="text-align: center;">
					<nav aria-label="Page navigation">
						<ul class="pagination" id="pagination">
							<!-- 动态插入分页 -->
						</ul>
					</nav>
				</td>
			</tr>
		</tfoot>
	</table>

	<!-- 编辑模态框 -->
	<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<h1 class="modal-title fs-5" id="editModalLabel">编辑</h1>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label for="inputDname" class="col-sm-2 control-label">权限名称</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="inputDname" placeholder="请输入权限名称">
							</div>
						</div>
						<div class="form-group">
							<label for="description" class="col-sm-2 control-label">权限描述</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="description" placeholder="请输入权限描述">
							</div>
						</div>
						<div class="form-group">
							<label for="editStatus" class="col-sm-2 control-label">权限状态</label>
							<div class="col-sm-10">
								<div class="checkbox">
									<label>
										<input type="radio" value="0" name="editState"> 启用
									</label>
									<label>
										<input type="radio" value="1" name="editState"> 禁用
									</label>
								</div>
							</div>
						</div>

					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" onclick="handleSave()">保存</button>
				</div>
			</div>
		</div>
	</div>
	<!-- 删除模态框 -->
	<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<h1 class="modal-title fs-5" id="deleteModalLabel">删除确认</h1>
				</div>
				<div class="modal-body">
					<div id="cancel" class="fs-6 "></div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="button" class="btn btn-danger" onclick="handleDelConfirm()">确认删除</button>
				</div>
			</div>
		</div>
	</div>
	<!-- 添加权限模态框 -->
	<div class="modal fade" id="addDictModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
							aria-hidden="true">&times;</span></button>
					<h4 class="modal-title" id="myModalLabel">添加权限</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label for="addInputDname" class="col-sm-2 control-label">权限名称</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="addInputDname" placeholder="请输入权限名称">
							</div>
						</div>

						<div class="form-group">
							<label for="inputStatus" class="col-sm-2 control-label">权限状态</label>
							<div class="col-sm-10">
								<div class="checkbox">
									<label>
										<input type="radio" value="0" name="dstate"> 启用
									</label>
									<label>
										<input type="radio" value="1" name="dstate"> 禁用
									</label>
								</div>
							</div>
						</div>
						<div class="form-group">
							<label for="inputStatus" class="col-sm-2 control-label note-label">权限描述</label>
							<div class="col-sm-10">

								<textarea id="note" class="form-control" maxlength="200"
									placeholder="请在此输入备注信息..."></textarea>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" onclick="onSave()">保存</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 权限详情列表模态框 -->
	<div class="modal fade" id="dictDetailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel">
		<div class="modal-dialog modal-lg" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
							aria-hidden="true">&times;</span></button>
					<h4 class="modal-title" id="detailModalLabel">权限详情列表</h4>
				</div>
				<div class="modal-body">
					<div class="row">
						<div class="col-md-12">
							<div class="panel panel-default">
								<div class="panel-heading">
									<h5 id="detailTitle">权限详情</h5>
								</div>
								<div class="panel-body">
									<table class="table table-bordered table-striped table-condensed">
										<thead>
											<tr>
												<th>#</th>
												<th>权限标签</th>
												<th>权限键值</th>
												<th>排序</th>
												<th>状态</th>
												<th>备注</th>
												<th>创建时间</th>
												<th>操作</th>
											</tr>
										</thead>
										<tbody id="dict-detail-tbody">
											<!-- 动态插入权限详情数据 -->
										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" onclick="addDictDetail()">添加详情</button>
				</div>
			</div>
		</div>
	</div>
	<script>
		let currentPage = 1;
		let pageSize = 10;
		let editData = null;
		let deleteId = 0;
		let rolesList = []

		function fetchDictData(pageNum = 1, pageSize = 10) {
			axios.get(`http://localhost/role/roles/${pageNum}/${pageSize}`)
				.then(res => {
					const data = res.data.data;
					const total = data.total;
					rolesList = data.list
					renderTable(data.list);
					renderPagination(data.pageNum, data.pageSize, data.total);
				})
				.catch(err => {
					alert('数据加载失败');
				});
		}

		function renderTable(list) {
			const tbody = document.getElementById('dict-tbody');

			tbody.innerHTML = '';
			list.forEach((item, idx) => {
				tbody.innerHTML += `
			  <tr>
				<td>${item.rid}</td>
				<td>${item.roleName}</td>
				<td>${item.description}</td>
				<td>${item.status == 0 ? '启用' : '禁用'}</td>
				<td>${item.createdBy || ''}</td>
				<td>${item.updatedBy || ''}</td>
				<td>${item.createdTime || ''}</td>
				<td>${item.updatedTime || ''}</td>
				<td>
				  <button class="btn btn-primary btn-xs"  data-toggle="modal" data-target="#editModal" onclick="handleEdit(${item.rid})">编辑</button>
				<button class="btn btn-info btn-xs" data-toggle="modal" data-target="#dictDetailModal" onclick="fetchDictDetails(${item.rid})" >列表</button>
				  <button class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deleteModal" onclick="handleDelete(${item.rid})">删除</button>
				</td>
			  </tr>
			`;
			});
		}



		async function handleEdit(rid) {

			const name = rolesList.find(item => item.rid == rid).roleName

			const res = await axios.get(`http://localhost/role/find/${name}`);
			if (res.data.code != 200) return alert(res.data.message);

			editData = res.data.data;
			const forms = {
				editInput: document.getElementById('inputDname'),
				description: document.getElementById('description'),
				editStatus: document.querySelectorAll('input[name="editState"]'),
			}
			console.log("dd ", res.data.data);

			forms.editInput.value = res.data.data.roleName;
			forms.description.value = res.data.data.description;
			forms.editStatus.forEach(el => {
				if (el.value == res.data.data.status) {
					el.checked = true;
				}
			});

		}

		async function handleSave() {
			const forms = {
				roleName: document.getElementById('inputDname'),
				description: document.getElementById('description'),
				status: document.querySelector('input[name="editState"]:checked'),
			}
			const data = {
				rid: editData.rid,
				roleName: forms.roleName.value,
				description: forms.description.value,
				status: parseInt(forms.status.value),
				updatedBy:"sys"
			}


			const newdata = { ...editData, ...data };
console.log("newdata", newdata);

			try {
				const res = await axios.post(`http://localhost/role/update`, newdata);
				console.log("res", res);
				
				if (res.data.code == 200) {
					alert('保存成功');
					$('#editModal').modal('hide');
					fetchDictData();
				}
				else {
					alert(res.data.message);
				}
			} catch (error) {
				console.log(error);


			}

		}

		async function handleDelete(id) {
			const res = await axios.get(`http://localhost/dict/find/${id}`);
			deleteId = id;
			const html = document.querySelector("#cancel")
			if (res.data.code == 200) {
				html.innerText = `确定要删除数据权限:${res.data.data.dname}吗？`
			}

		}
		async function handleDelConfirm() {
			const res = await axios.delete(`http://localhost/dict/delete/${deleteId}`);
			if (res.data.code == 200) {
				fetchDictData();
				$('#deleteModal').modal('hide');
			}
		}

		function renderPagination(pageNum, pageSize, total) {
			const page = Math.ceil(total / pageSize);
			const pageCount = page >= 5 ? 5 : page;
			const pagination = document.getElementById('pagination');
			let html = '';
			console.log("curr", currentPage);
			html += `<li>
			<a href="#" aria-label="Previous" >
			  <span >总页数: ${page}</span>
			</a>
		  </li>`;
			html += `<li${pageNum === 1 ? ' class="disabled"' : ''}>
						<a href="#" aria-label="Previous" onclick="gotoPage(${pageNum - 1})">
						  <span aria-hidden="true">&laquo;</span>
						</a>
			</li>`;

			if (pageNum > 5) {
				for (let i = pageNum - 4; i <= pageNum; i++) {
					html += `<li${i === pageNum ? ' class="active"' : ''}>
						  <a href="#" onclick="gotoPage(${i})">${i}</a>
						</li>`;
				}
			}
			else {
				for (let i = 1; i <= pageCount; i++) {
					html += `<li${i === pageNum ? ' class="active"' : ''}>
			  			  <a href="#" onclick="gotoPage(${i})">${i}</a>
			  			</li>`;
				}
			}

			html += `<li${pageNum === pageCount ? ' class="disabled"' : ''}>
			<a href="#" aria-label="Next" onclick="gotoPage(${pageNum + 1})">
			  <span aria-hidden="true">&raquo;</span>
			</a>
		  </li>`;
			pagination.innerHTML = html;
		}

		function gotoPage(page) {
			if (page < 1) return;
			currentPage = page;
			fetchDictData(currentPage, pageSize);
		}

		// 页面加载时获取第一页
		fetchDictData(currentPage, pageSize);

		// 查询权限详情数据
		function fetchDictDetails(dictName) {
			const requestData = {
				dname: dictName
			};

			axios.post('http://localhost/dict/findAll', requestData)
				.then(res => {
					if (res.data.code === 200) {
						renderDictDetailTable(res.data.data);
					} else {
						alert('查询权限详情失败：' + res.data.message);
					}
				})
				.catch(err => {
					console.error('查询权限详情失败:', err);
					alert('查询权限详情失败，请检查网络连接');
				});
		}



		// 渲染权限详情表格
		function renderDictDetailTable(detailList) {
			const tbody = document.getElementById('dict-detail-tbody');
			tbody.innerHTML = '';

			if (!detailList || detailList.length === 0) {
				tbody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
				return;
			}

			detailList.forEach((item, idx) => {
				// 处理时间格式
				const formatTime = (timeStr) => {
					if (!timeStr) return '';
					return new Date(timeStr).toLocaleString();
				};

				tbody.innerHTML += `
					<tr>
						<td>${item.id}</td>
						<td>${item.dtag || ''}</td>
						<td>${item.dval || ''}</td>
						<td>${item.dorder || ''}</td>
						<td>${item.state == 0 ? '启用' : '禁用'}</td>
						<td>${item.mark || ''}</td>
						<td>${formatTime(item.createTime) || ''}</td>
						<td>
							<button class="btn btn-primary btn-xs" onclick="editDictDetail(${item.id})">编辑</button>
							<button class="btn btn-danger btn-xs" onclick="deleteDictDetail(${item.id})">删除</button>
						</td>
					</tr>

				`;
			});
		}

	</script>

	<script>
		// 添加权限数据
		async function onSave() {
			const forms = {
				dname: document.getElementById('addInputDname'),
				dstate: document.querySelector('input[name="dstate"]:checked'),
				mark: document.getElementById('note'),
			}
			const data = {
				roleName: forms.dname.value,
				status: parseInt(forms.dstate.value),
				description: forms.mark.value,
				updatedBy: '麒麟'
			}


			if (!data.roleName) {
				return alert('请输入权限名称');
			}
			if (data.status == undefined) {
				return alert('请选择权限状态');
			}
			try {
				const res = await axios.post(`http://localhost/role/add`, data);
				if (res.data.code == 200) {
					alert('权限添加成功');
					$('#editModal').modal('hide');
					fetchDictData();
				}
				if (res.data.code == -1) {
					alert('角色已存在');
				}

			} catch (error) {
				alert('权限添加失败', error);
				$('#editModal').modal('hide');
			}

		}

	</script>
</body>

</html